/**
 * 
 */
package com.antilia.infomaresme.data.dao.hibernate;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.antilia.infomaresme.data.dao.interfaces.IUserItemAlertsDao;
import com.antilia.infomaresme.data.dataobjects.Item;
import com.antilia.infomaresme.data.dataobjects.User;
import com.antilia.infomaresme.data.dataobjects.UserItemAlert;

/**
 * @author Ernesto
 *
 */
public class UserItemAlertsDao extends AbstractDaoHibernateImpl<UserItemAlert> implements IUserItemAlertsDao {

	/**
	 * @param domainClass
	 */
	public UserItemAlertsDao() {
		super(UserItemAlert.class);
	}
	
	public User loadById(String userId) {
		Criteria criteria = getSession().get().createCriteria(User.class);
		criteria.add(Restrictions.eq("userId", userId));
		@SuppressWarnings("unchecked")
		List<User> users = (List<User>)criteria.list();
		return users.size()>0?users.get(0): null;
	}

	@SuppressWarnings("unchecked")
	public List<UserItemAlert> getItems(User user, Item item, int start,int size) {
		Criteria criteria = getSession().get().createCriteria(UserItemAlert.class);
		criteria.setFetchSize(size);
		criteria.setFirstResult(start);
		configureCriteria(criteria, user, item);
		return (List<UserItemAlert>)criteria.list();
	}
	
	private void configureCriteria(Criteria criteria, User user, Item item) {
		if(item != null) {
			criteria.add(Restrictions.eq("item", item));
		}
		if(user != null) {
			criteria.add(Restrictions.eq("user", user));
		}
	}

	public Long countItems(User user, Item item) {
		Criteria criteria = session.get().createCriteria(UserItemAlert.class);
		criteria.setProjection(Projections.rowCount());
		configureCriteria(criteria, user, item);
		return (Long)(criteria.uniqueResult());
	}
	
	public UserItemAlert getAlert(User user, Item item) {
		Criteria criteria = getSession().get().createCriteria(UserItemAlert.class);
		if(user == null || item == null)
			return null;
		configureCriteria(criteria, user, item);
		@SuppressWarnings("unchecked")
		List<UserItemAlert> list = (List<UserItemAlert>)criteria.list();
		return list.size()>0?list.get(0): null;
	}
	
	public List<UserItemAlert> findAlerts(Item item) {
		Criteria criteria = getSession().get().createCriteria(UserItemAlert.class);
		if(item != null) {
			criteria.add(Restrictions.eq("item", item));
		}
		@SuppressWarnings("unchecked")
		List<UserItemAlert> list = (List<UserItemAlert>)criteria.list();
		return list;
	}

}
